﻿using CQRS.Events;
using CQRS.Reports;
using CQRS.Sample.Domain.Events;
using CQRS.Sample.Domain.ReportDtos;

namespace CQRS.Sample.Domain.EventHandlers
{
    public class PlaneHasCrashedEventHandler : IEventHandler<PlaneHasCrashedEvent>
    {
        private readonly IReportingRepository _reportingRepository;

        public PlaneHasCrashedEventHandler(IReportingRepository reportingRepository)
        {
            _reportingRepository = reportingRepository;
        }

        #region IEventHandler<PlaneHasCrashedEvent> Members

        public void Execute(PlaneHasCrashedEvent theEvent)
        {
            _reportingRepository.Update<PlaneReport>
                (new QueryCriteria().AddCriteria("HasCrashed", true),
                 new QueryCriteria().AddCriteria("Id", theEvent.PlaneId));
            _reportingRepository.Update<PlaneDetailsReport>
                (new QueryCriteria().AddCriteria("HadCrashed", true),
                 new QueryCriteria().AddCriteria("Id", theEvent.PlaneId));
            _reportingRepository.Update<PlaneHistoryReport>
                (new QueryCriteria().AddCriteria("HadCrashed", true),
                 new QueryCriteria().AddCriteria("Id", theEvent.PlaneId));

            var planeCrashReport = new PlaneCrashReport(theEvent.PlaneId,
                                   theEvent.Location, theEvent.Aboard, theEvent.Fatalities,
                                                        theEvent.Route, theEvent.CrashDate);
            _reportingRepository.Save(planeCrashReport);
        }

        #endregion
    }
}